class EventEmitter {
    constructor() {
        this.cache = {} // 存储名字和幻术的对应关系
    }
    on (name, fn) { // 订阅函数方法
        if (this.cache[name]) { // 有这个时间名
            this.cache[name].push(fn) // 放入函数
        } else {
            this.cache[name] = [fn]
        }
    }
    off (name, fn) { // 取消时间方法
        if (this.cache[name] === undefined) return
        let tasks = this.cache[name] // 找到这个task 
        let index = tasks.findIndex(f => f === fn || f.callback === fn) // 找个这个的索引
        if (index >= 0) { // 删除
            tasks.splice(index, 1)
        }
    }
    emit (name, once = false, ...args) { // 发布事件
        if (this.cache[name]) {
            let tasks = this.cache[name].slice() // 拷贝一份改时间
            for (let fn of tasks) { // 遍历事件传入参数
                fn(...args)
            }
            if (once) { // 如果只有一次 删除该事件
                delete this.cache[name]
            }
        }
    }
}

// class EventEmitter {
//     constructor() {
//         this.cache = {}
//     }
//     on (name, fn) {
//         if (this.cache[name]) {
//             this.cache[name].push(fn)
//         } else {
//             this.cache[name] = [fn]
//         }
//     }
//     off (name, fn) {
//         if (this.cache[name] === undefined) return
//         let index = this.cache[name].findIndex(item => item === fn)
//         if (index > -1) {
//             this.cache[name].splice(index, 1)
//         }
//     }
//     emit (name, once = false, ...args) {
//         let tasks = this.cache[name]
//         for (let fn of tasks) {
//             fn(...args)
//         }
//         if (once) {
//             delete this.cache[name]
//         }
//     }
// }



// 测试
let eventBus = new EventEmitter()
let fn1 = function (name, age) {
    console.log(`${name} ${age}`)
}
let fn2 = function (name, age) {
    console.log(`hello, ${name} ${age}`)
}
eventBus.on('aaa', fn1)
eventBus.on('aaa', fn2)

eventBus.emit('aaa', false, '布兰', 12)
eventBus.off('aaa', fn2)
eventBus.emit('aaa', false, '1布兰', 12)